import Vue from 'vue';
import Router from 'vue-router';

import routes from './routes.js';
import store from '../store/index.js';

Vue.use(Router);

const router = new Router({
	mode: 'history',
	routes
});

router.beforeEach((to, from, next) => {
	// 设置网站标题
	const title = to.meta.title;
	if (title) {
		document.title = title + ' - 小米商城管理系统';
	}

	// 判断是否登录
	if (to.meta.noLogin) {
		next();
	} else {
		if (!store.getters.hasLogin) {
			// 从会话缓存中获取登录信息
			let loginUser = sessionStorage.getItem('loginUser');
			if (loginUser) {
				loginUser = JSON.parse(loginUser);
				if (loginUser.token) {
					store.commit('login', loginUser);
					next();
					return;
				}
			}
			router.replace('/login');
		} else {
			next();
		}
	}
});

export default router;
